//
// Created by fang on 20-5-5.
//
#include <malloc.h>
#include <string.h>
#include "segbuf.h";
#include "str.h"

//初始化一个buf
seg_buf* seg_buf_init() {
    seg_buf* buf;
    buf = (seg_buf*)malloc(sizeof(struct s_seg_buf));
    buf->data = (char*)malloc(SEG_BUF_SIZE);
    buf->len = SEG_BUF_SIZE;
    buf->data_len = 0;
}

/**
 * 缓存追加数据
 *
 * @param buf
 * @param str
 */
void seg_buf_append(seg_buf* buf, char* str) {
    int len = 0;
    len = strlen(str);
    return seg_buf_appendn(buf, str, len);
}

/**
 * 追加N个字符
 *
 * @param buf
 * @param str
 * @param n
 */
void seg_buf_appendn(seg_buf* buf, char* str, int n) {
    int len = n;
    char *tmp;

    if(n<=0) return;

    //检查内存
    //TODO 有优化余地
    while(buf->len <= (buf->data_len + len)) {
        buf->data = realloc(buf->data, buf->len + SEG_BUF_SIZE);
        buf->len = buf->len + SEG_BUF_SIZE;
    }

    //复制合并内容
    tmp = buf->data;
    tmp += buf->data_len;
    strncpy(tmp, str, len);
    //tmp+=len;
    //*tmp = '\0';
    buf->data_len += len;
    return;
}

/**
 * 缓存追加数据
 *
 * @param buf
 * @param str
 */
void seg_buf_append_str(seg_buf* buf, seg_str* str) {
    int len = 0;
    char *tmp;
    //检查内存
    //TODO 有优化余地
    while(buf->len < (buf->data_len + str->len)) {
        buf->data = realloc(buf->data, buf->len + SEG_BUF_SIZE);
        buf->len = buf->len + SEG_BUF_SIZE;
    }

    //复制合并内容
    tmp = buf->data;
    tmp += buf->data_len;
    strncpy(buf->data, str->str, str->len+1);
    buf->data_len += len;
    return;
}

/**
 * 释放缓存
 *
 * @param buf
 */
void seg_buf_free(seg_buf* buf) {
    free(buf->data);
    free(buf);
}
